package com.weixin.project.Util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class WeChatUtil {
    private static String appId = "wx3e3cb3fa9c608af1";
    private static String secret = "361b263157e7c430756f90ad042aae4e";
    private static String randomStr = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_____";
    public static JSONObject getSessionKeyOrOpenId(String code) {
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> requestUrlParam = new HashMap<>();
        // https://mp.weixin.qq.com/wxopen/devprofile?action=get_profile&token=164113089&lang=zh_CN
        //小程序appId
        requestUrlParam.put("appid", appId);
        //小程序secret
        requestUrlParam.put("secret", secret);
        //小程序端返回的code
        requestUrlParam.put("js_code", code);
        //默认参数
        requestUrlParam.put("grant_type", "authorization_code");
        //发送post请求读取调用微信接口获取openid用户唯一标识

        JSONObject jsonObject = JSON.parseObject(HttpClientUtil.doPost(requestUrl, requestUrlParam));
        System.out.println("===========================================================");
        System.out.println(jsonObject);
        System.out.println("===========================================================");

        return jsonObject;
    }

    public static String generateRandomName(){
        StringBuilder sb = new StringBuilder();
        sb.append("微信用户");
        for (int i = 0; i < 10; i++) {
            sb.append(randomStr.charAt(new Random().nextInt(randomStr.length())));
        }
        return sb.toString();
    }
}
